package com.euq.log;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogAspect {

    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Before("@annotation(Log)")
    public void logBefore() {
        logger.info("Method execution started...");
    }

    @After("@annotation(Log)")
    public void logAfter() {
        logger.info("Method execution finished.");
    }

    @Around("@annotation(Log)")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        logger.info("Method execution started: " + joinPoint.getSignature().getName());

        Object result = null;
        try{
            result = joinPoint.proceed();
        }catch (Throwable throwable){
            logger.error("Exception occurred in method: " + joinPoint.getSignature().getName(), throwable);
            throw throwable;
        }

        long end = System.currentTimeMillis();
        logger.info("Method execution finished: " + joinPoint.getSignature().getName());
        logger.info("Execution time: " + (end - start) + "ms");

        return result;
    }
}
